import axios from "axios";
import router from "../router";

const basic = ({ url, data, needLogin }, method = "post") => {
  let promise = new Promise((resolve, reject) => {
    //网络请求
    let config = {
      baseURL: process.env.VUE_APP_BASE_API,
      url,
      // url: document.location.protocol + process.env.VUE_APP_BASE_API + url,
      data,
      method,
      header: {
        "content-type": "application/json",
        'Authorization': localStorage.getItem("token") || ""
      }
    };
    axios(config)
      .then(res => {
        //服务器返回数据
        console.log(`${method} res------> ${url} ${JSON.stringify(data)}`, res);
        if (res.status === 200) {
          if (res.data && res.data.code === 200) {
            // resolve 只返回data
            // reject 只返回erroMsg
            resolve(res.data.response_data);
            // const err = check.error(res.data);
            // console.log("0", err)
          } else {
            reject({message: res.data.message});
          }
        } else if (res.status === 401) {
          // token.checkLogin(false);
          if (needLogin) {
            router.replace({
              path: "/login"
            });
          } else reject({message: "401"});
        } else if (res.status === 404) {
          reject({message: "接口不存在 404"});
        } else if (res.status === 500) {
          reject({message: "请稍后再试 500"});
        } else if (res.status === 503) {
          reject({message: "Service Unavailable 503"});
        } else {
          //返回错误提示信息
          reject({message: res.data.message});
        }
      })
      .catch((res) => {
        reject({message: "网络出错 " + res});
      });
  });
  return promise;
};
const post = ({ url = "/", data = {}, needLogin = true }) => {
  return basic({ url, data, needLogin }, "post");
};
const get = ({ url = "/", data = {}, needLogin = true }) => {
  return basic({ url, data, needLogin }, "get");
};
const put = ({ url = "/", data = {}, needLogin = true }) => {
  return basic({ url, data, needLogin }, "put");
};
const del = ({ url = "/", data = {}, needLogin = true }) => {
  return basic({ url, data, needLogin }, "delete");
};

export default {
  post,
  get,
  put,
  del
};
